/**
 * Copyright (c) 2016 上海好易信息技术有限公司 版权所有
 * Shang hai HY System Limited. All rights reserved.
 */
package com.taotao.common.utils;

import java.util.ArrayList;

/** 
* @ClassName: MyStringBuilder 
* @Description: 字符写入器 
* @author 王东升 
* @date 2016年6月8日 上午10:43:25 
*  
*/
public class StringBuilder {
	private final static int max_len = 1024;
	private int len;
	private ArrayList<char[]> list = new ArrayList<char[]>();
	private char[] cur;
	private int pos;
	
	/** 
	* @Title: 构造函数 
	*/
	public StringBuilder()
	{
		this.cur = new char[max_len];
		this.list.add(this.cur);
	}
	/** 
	* @Title: write 
	* @Description: 写入字符串 
	* @param str 待写入字符串
	*/
	public void write(String str){
		for(int i =0; i < str.length();i++){
			write(str.charAt(i));
		}
	}
	/** 
	* @Title: write 
	* @Description: 字符串部分写入 
	* @param str 待写入字符串
	* @param s 开始位置
	* @param e 结束位置
	*/
	public void write(String str,int s,int e){
		for(int i =s;i < e;i++){
			write(str.charAt(i));
		}
	}
	/** 
	* @Title: write 
	* @Description: 写入字符
	* @param c 待写入字符
	*/
	public void write(char c){
		if(pos == this.cur.length){
			this.cur = new char[this.cur.length*2];
			this.list.add(this.cur);
			pos = 0;
		}
		this.cur[pos++] = c;
		len++;
	}
	/* (non-Javadoc)
	 * @see java.lang.Object#toString()
	 */
	public String toString(){
		if(this.list.size() == 1){
			return new String(this.cur,0,len);
		}
		char[] ret = new char[len];
		int li_len = len;
		int li_s = 0;
		for(int i =0; i < this.list.size();i++){
			int li_cy =  li_len>this.list.get(i).length?this.list.get(i).length:li_len;
			System.arraycopy(this.list.get(i), 0, ret, li_s,li_cy);
			li_len = li_len - li_cy;
			li_s = li_s + li_cy;
		}
		return new String(ret);
	}
}
